package edu.xhu.check.util;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.http.webservice.SoapUtil.createClient;

@Getter
@Setter
@Component
@Slf4j
@ConfigurationProperties(prefix = "aliyun")
public class Scan {

    private static final String accessKeyId = "LTAI5tLrHzjBw2PH6sZ1K2vH";
    private static final String secret = "e5DCZTdp8WjImOrVxOHB8VohGlpP2Q";

    public static Map<String, String> greenTextScan(String content) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(secret);
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-shanghai");
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);
        //构造返回
        Map<String, String> resultMap = new HashMap<>();
        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().isEmpty()) {
            resultMap.put("suggestion", "检测内容为空");
            System.out.println("text moderation content is empty");
            return resultMap;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        /*
        文本检测service：内容安全控制台文本增强版规则配置的serviceCode，示例：chat_detection
        */
        textModerationRequest.setService("chat_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            // 自动路由。
            if (response != null) {
                // 服务端错误，区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
                    config.setRegionId("cn-beijing");
                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
                    client = new Client(config);
                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }

            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        if (data.getLabels().isEmpty() && data.getReason().isEmpty()) {
                            resultMap.put("suggestion", "pass");
                        } else {
                            resultMap.put("suggestion", "block");
                            resultMap.put("labels", data.getLabels());
                            resultMap.put("reason", data.getReason());
                        }
                    } else {
                        System.out.println("text moderation not success. code:" + code);
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return resultMap;
    }

    /**
     * 图片检测
     */

    public static ImageModerationResponse invokeFunction(String endpoint) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(secret);
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-shanghai");
        config.setEndpoint(endpoint);
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();

        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", "https://bili-image.oss-cn-hangzhou.aliyuncs.com/%E3%80%90%E5%8A%A8%E7%94%BB%E3%80%91%E4%B8%BA%E4%BB%80%E4%B9%88%E6%89%80%E6%9C%89%E4%BA%BA%E9%83%BD%E6%AF%94%E6%88%91%E5%A5%BD%EF%BC%9F.jpg");
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
        // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    public static Map<String, Object> test() throws Exception {
        ImageModerationResponse response = invokeFunction("green-cip.cn-shanghai.aliyuncs.com");
        //构造返回
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 自动路由。
            if (response != null) {
                //区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
                    response = invokeFunction("green-cip.cn-beijing.aliyuncs.com");
                }
            }

            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                            resultMap.put("labels", result.getLabel());
                            resultMap.put("confidence", result.getConfidence());
                        }
                    } else {
                        System.out.println("image moderation not success. code:" + body.getCode());
                    }
                } else {
                    resultMap.put("code", response.getStatusCode());
                    resultMap.put("msg", response.getBody().getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 视频检测
     */
    public static Map<String, Object> testMp4() throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(secret);
        //接入区域和地址请根据实际情况修改。
        config.setRegionId("cn-shanghai");
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        Client client = new Client(config);

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url"
                , "https://bili-video.oss-cn-hangzhou.aliyuncs.com/%5BLPL%E6%98%A5%E5%AD%A3%E8%B5%9B%5D3%E6%9C%8823%E6%97%A5RNGvsIG.mp4"
        );
        serviceParameters.put("ossBucketName", "bili-video");
        serviceParameters.put("ossObjectName", "[LPL春季赛]3月23日RNGvsIG.mp4");
        serviceParameters.put("ossRegionId", "cn-hangzhou");

        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetection
        videoModerationRequest.setService("videoDetection");
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                resultMap.put("code", result.getCode());
                resultMap.put("requestId", result.getRequestId());
                resultMap.put("msg", result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    resultMap.put("taskId", data.getTaskId());
                } else {
                    resultMap.put("video moderation not success. code:", code);
                }
            } else {
                resultMap.put("response not success. status:", response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    public static Map<String, Object> getVideoResult(String taskId) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(secret);
        //接入区域和地址请根据实际情况修改。
        config.setRegionId("cn-shanghai");
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        Client client = new Client(config);

        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);
        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        // 检测类型：videoDetection
        videoModerationResultRequest.setService("videoDetection");
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResultResponseBody result = response.getBody();
                resultMap.put("code", result.getCode());
                resultMap.put("requestId", result.getRequestId());
                resultMap.put("msg", result.getMessage());
                if (200 == result.getCode()) {
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                    resultMap.put("dataId", data.getDataId());
                    resultMap.put("audioResult", JSON.toJSONString(data.getAudioResult()));
                    resultMap.put("frameResult", JSON.toJSONString(data.getFrameResult()));
                    resultMap.put("frameNum", data.getFrameResult().getFrameNum());
                }
            } else {
                resultMap.put("code", response.getStatusCode());
                resultMap.put("msg", response.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException();
        }
        return resultMap;
    }


}